<template>
  <a-modal 
    :visible="visible"
    okText="提交" 
    cancelText="关闭" 
    :title="title"
    :maskClosable="false"
    :keyboard="false"
    @cancel="$emit('cancel')" 
    width="80%"
    @ok="handleSubmit">
    <div class="scroll-box">
      <a-table 
        :pagination="false" 
        :defaultExpandAllRows="true" 
        rowKey="id"
        :row-selection="rowSelection" 
        :columns="columns" 
        :data-source="menuList"></a-table>
    </div>
  </a-modal>
</template>
<script>
export default {
  name: 'set-permission',
  props: {
    record: {
      type: Object,
      default() {
        return {}
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
  },
  computed: {
    title () {
      return '权限设置'
    },

  },
  data () {
    return {
      menuList: [],
      rowSelection: {selectedRowKeys: []},
      columns:  [{
          title: '权限名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '权限编码',
          dataIndex: 'code',
          key: 'code',
        },
        {
          title: '创建时间',
          dataIndex: 'createDate',
          key: 'createDate',
        }
      ]
    }
  },
  watch: {
    visible (value) {
      if (!this.record.id) return
      if (value) {
        this.rowSelection.selectedRowKeys = []
        this.getInfo()
        this.getMenuList()
      }
    }
  },
  mounted () {
    this.rowSelection.onChange = (selectedRowKeys, selectedRows) => {
      this.rowSelection.selectedRowKeys = selectedRowKeys
    }
  },
  methods: {
    getMenuList () {
      if (this.menuList && this.menuList.length) return 
      this.$get('/sys/permissions/tree').then(res => {
        if (res && res.returnCode === 1000) {
          this.menuList = res.dataInfo
        }
      })
    },
    getInfo () {
      if (!this.record.id) return
      const url = `/sys/roles/${this.record.id}/permissions`
      this.$get(url).then(res => {
        if (res && res.returnCode === 1000) {
          this.rowSelection.selectedRowKeys = res.dataInfo
        }
      })
    },
    handleSubmit () {
      const url = `/sys/roles/${this.record.id}/permissions/choose`
      const selected =this.rowSelection.selectedRowKeys
      const list = selected && selected.length && selected.map(item => ({permissionId: item})) || []
      this.$post(url, {list}).then(res => {
        if (res && res.returnCode === 1000) {
          this.$message.success('保存成功！')
          this.$emit('cancel')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.scroll-box {
  max-height: 600px;
  overflow: auto;
}
</style>